<template>
	<div class="contents">
		<div class="neworder">
			<p class="newOrder-title">
				<strong>.</strong>
				基本信息
			</p>
			<div class="new-order-main">
				<el-form :inline="true" :model="formData" class="demo-form-inline">
					<el-form-item label="客户">
						<el-autocomplete v-model="formData.customerName" :fetch-suggestions="querySearchAsync"
							placeholder="请输入客户名称/客户编号" @select="handleSelect" clearable @clear="clearUserName">
						</el-autocomplete>
					</el-form-item>
					<!-- <el-form-item label="发货日期">
						<el-date-picker v-model="formData.deliveryDate" value-format="yyyy-MM-dd" type="date"
							placeholder="选择日期" :disabled="handleshow"></el-date-picker>
					</el-form-item> -->
					<!-- <el-form-item label="发货时间">
						<el-select v-model="formData.deliveryTime" :disabled="handleshow" placeholder="请选择">
							<el-option label="06:00-09:00" value="06:00-09:00"></el-option>
						</el-select>
					</el-form-item> -->
				</el-form>
			</div>
			<!-- <p class="newOrder-title" style="display: flex;">
				<span style="margin-right: 30px;">标签：</span>
				<el-checkbox-group v-model="formData.tags">
					<el-checkbox v-for="(item,index) in tagList" :key="index" :label="item.name" :value="item.id">
					</el-checkbox>
				</el-checkbox-group>
			</p> -->
			<p class="newOrder-title">
				<strong>.</strong>
				收货信息
			</p>
			<div class="newOrder-address">
				<span>收货人：{{ userData.name }}</span>
				<span>电话：{{ userData.customerAddress.phone }}</span>
				<span>收货地址：{{ userData.customerAddress.addr }}</span>
			</div>
			<div v-show="!handleshow">
				<div class="newOrder-title">
					<strong>.</strong>
					订购商品清单
					<!-- <div class="newOrder-operation">
						<span>智能录单</span>
						<span>从历史订单复制新增</span>
					</div> -->
				</div>
				<div class="new-order-main" style="border-bottom: none;">
					<el-form :inline="true" :model="formData" class="demo-form-inline">
						<el-form-item label="商品">
							<el-input placeholder=" " class="input-with-select" disabled>
								<el-button slot="append" icon="el-icon-plus" type="success" @click="dialogGoods = true">
								</el-button>
							</el-input>
						</el-form-item>
						<!-- <el-form-item label="数量">
							<el-input placeholder="输入订购数" style="width: 100px; margin-right: 20px;"></el-input>
							<el-button type="success" icon="el-icon-plus">添加</el-button>
						</el-form-item> -->
						<!-- <el-form-item label="" style="float: right;">
							<el-button>表头设置</el-button>
						</el-form-item> -->
					</el-form>
				</div>
				<el-dialog title="请选择商品" :close-on-click-modal="false" custom-class="modals" :show-close="false"
					:visible.sync="dialogGoods" width="85%">
					<el-row :gutter="5" type="flex" align="middle">
						<el-col :span="16">
							<el-cascader></el-cascader>
						</el-col>
						<el-col :span="15">
							<el-cascader></el-cascader>
						</el-col>
						<el-col>
							<el-input placeholder="请输入商品名称/编码进行搜索">
								<el-button slot="append" icon="el-icon-search"></el-button>
							</el-input>
						</el-col>
						<el-col :span="5">
							<el-checkbox>显示库存为"0"的商品</el-checkbox>
						</el-col>
						<el-col>
							<span style="color: #03ac54; margin-left: 10px;">
								小贴士：鼠标单击表格行即可直接选中或修改
							</span>
						</el-col>
					</el-row>
					<el-table ref="multipleTable" :data="goodsData.list" border style="width: 100%; margin-top: 10px;"
						@select="selectGoods" height="449px">
						<el-table-column type="selection" width="55" align="center"></el-table-column>
						<el-table-column label="商品图片" prop="goodsImages.path">
							<template slot-scope="scope">
								<el-image :src="scope.row.goodsImages.path" style="width: 50px; height: 50px;" />
							</template>
						</el-table-column>
						<el-table-column prop="name" label="名称编码" width="220">
							<template slot-scope="scope">
								<div>{{ scope.row.name }}</div>
								<div>{{ scope.row.code }}</div>
							</template>
						</el-table-column>
						<el-table-column prop="goodsPrice.unit" label="单位"></el-table-column>
						<el-table-column prop="category.name" label="商品分类"></el-table-column>
						<el-table-column prop="warename" label="仓库"></el-table-column>
						<el-table-column prop="goodsPrice.price" label="价格"></el-table-column>
						<el-table-column prop="goodsPrice.stock" label="库存"></el-table-column>
						<el-table-column prop="qty" label="数量">
							<template slot-scope="scope">
								<el-input v-model="scope.row.qty"></el-input>
							</template>
						</el-table-column>
					</el-table>
					<el-pagination background layout="total, prev, pager, next,sizes, jumper"
						:page-size="goodsData.pageSize" :page-sizes="[10, 20, 30, 40]" style="text-align: left;"
						:total="goodsData.total" @current-change="checkPage" @size-change="sizeChange" />
					<span slot="footer" class="dialog-footer">
						<el-button @click="dialogGoods = false">取 消</el-button>
						<el-button type="primary" @click="handleSelectTwo">
							确 认
						</el-button>
					</span>
				</el-dialog>
				<el-table :data="tableData" border style="width: 100%;">
					<el-table-column type="index" width="50" label="序号"></el-table-column>
					<el-table-column label="商品" width="180">
						<template slot-scope="scope">
							<div>{{ scope.row.name }}</div>
							<div style="color: rgb(153, 153, 153);">{{ scope.row.code }}</div>
						</template>
					</el-table-column>
					<el-table-column prop="detail" label="描述"></el-table-column>
					<el-table-column prop="goodsPrice.unit" label="单位"></el-table-column>
					<el-table-column label="出库数量">
						<template slot-scope="scope">
							<el-input v-model="scope.row.qty"></el-input>
						</template>
					</el-table-column>
					<el-table-column prop="goodsPrice.price" label="单价(元)">
						<template slot-scope="scope">
							<el-input v-model="scope.row.goodsPrice.price"></el-input>
						</template>
					</el-table-column>
					<el-table-column prop="address" label="金额(元)">
						<template slot-scope="scope">
							{{ scope.row.qty * scope.row.goodsPrice.price }}
						</template>
					</el-table-column>
					<el-table-column prop="areaname" label="库区库位"></el-table-column>
					<el-table-column prop="remarks" label="备注">
						<template slot-scope="scope">
							<el-input v-model="scope.row.remarks"></el-input>
						</template>
					</el-table-column>
					<el-table-column prop="address" label="操作">
						<template slot-scope="scope">
							<el-button size="mini" type="text" @click="handleDel(scope.$index,scope.row)">
								删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
				<!-- <el-table ref="singleTable" :data="tableData" highlight-current-row style="width: 100%;">
					<el-table-column type="index" width="50" label="序号"></el-table-column>
					<el-table-column label="商品图片"></el-table-column>
					<el-table-column label="商品名称"></el-table-column>
					<el-table-column label="描述"></el-table-column>
					<el-table-column label="单位"></el-table-column>
					<el-table-column label="现有库存"></el-table-column>
					<el-table-column label="下单数量"></el-table-column>
					<el-table-column label="下单单价"></el-table-column>
					<el-table-column label="下单小计"></el-table-column>
					<el-table-column label="最后一次进价"></el-table-column>
					<el-table-column label="最后一次下单"></el-table-column>
					<el-table-column label="备注"></el-table-column>
				</el-table> -->
				<div class="newOrder-amount">
					<span>合计金额：¥</span>
					<span>{{ totalPrice }}</span>
				</div>
				<!-- <div class="newOrder-remark" style="display: flex; align-items: center;">
					<div style="width: 80px;">订单备注</div>
					<el-input placeholder="输入订单备注" maxlength="64" show-word-limit style="width: 100%;"></el-input>
				</div> -->
			</div>

			<div class="newOrder-feature">
				<!-- <el-button :disabled="handleshow" :type="handleshow ? '' : 'primary'">
					核对订单
				</el-button> -->
				<el-button :disabled="handleshow" :type="handleshow ? '' : 'primary'" @click="handleSave">
					保存并返回列表
				</el-button>
				<!-- <el-button :disabled="handleshow" :type="handleshow ? '' : 'primary'">
					保存并继续新增
				</el-button> -->
				<el-button @click="goBack">取消</el-button>
			</div>
		</div>
	</div>
</template>

<script>
	import { getOrderAdd, getOrderitemAdd } from '@/api/order'
	import { getList } from '@/api/customer/customerProfile'
	import { getGoodsQuery } from '@/api/goodslist'
	import { handleActivePath } from '@/utils/routes'
	import { mapActions } from 'vuex'
	import {
	  getUnitQuery,
	  getUnitEdit,
	  getUnitAdd,
	  getUnitDel,
	} from '@/api/profile'
	export default {
		data() {
			return {
				tagList:[],
				formData: {
					wsId: 1,
					customerName: '',
					customerId: '',
					deliveryDate: '',
					deliveryTime: '',
					type: 'B',
					customerAddr: '',
					customerPhone: '',
					origin: '后台创建',
					salesId: 1,
					total: 300,
					cuser: this.$store.state.user.username,
					tags:[],
					status:1
				},
				dataFilter: {
					pagesize: 10,
					current: 1,
				},
				selectData: [],
				tableData: [],
				userData: {
					customerAddress: {},
				},
				handleshow: true,
				dialogGoods: false,
				goodsData: [], //商品所有信息
			}
		},
		created() {
			this.getListData()
			this.Taginit()
		},
		computed: {
			totalPrice() {
				let finalPrice = 0
				for (let book of this.tableData) {
					finalPrice += book.qty * book.goodsPrice.price
				}
				return finalPrice
			},
		},
		mounted() {
			console.log(this.$route.query.status)
		},
		methods: {
			async Taginit() {
				const res = await getUnitQuery({
				  code: 'order_name',
				})
				this.tagList = res.data
			},
			handleDel(index, item) {
				this.tableData.splice(index, 1)
				this.$refs.multipleTable.toggleRowSelection(item);
			},
			...mapActions({
				delVisitedRoute: 'tabs/delVisitedRoute',
			}),

			async getListData() {
				const res = await getGoodsQuery(this.dataFilter)
				this.goodsData = res.data
			},
			async querySearchAsync(queryString, cb) {
				setTimeout(async () => {
					const ret = await getList(1, 20, {})
					let callBackArr = []
					const res = ret.data.list
					res.forEach((item) => {
						if (item.name.indexOf(queryString) > -1) {
							callBackArr.push(item)
						}
					})
					var newarr = callBackArr.map((item) => {
						return {
							...item,
							value: item.name,
							label: item.id,
						}
					})
					if (callBackArr.length == 0) {
						cb([{ value: '暂无数据', name: '暂无数据' }])
					} else {
						cb(newarr)
					}
				}, 1000)
			},
			handleSelectTwo() {
				if (this.selectData.length !== 0) {
					this.tableData = this.selectData
					this.dialogGoods = false
				} else {
					this.$confirm('请选择需要添加的商品', '操作失败', {
						showClose: false,
						showCancelButton: false,
						closeOnClickModal: false,
						confirmButtonText: '确定',
						type: 'error',
					})
				}
			},
			handleSelect(item) {
				console.log(11111111111111111111, item)
				this.formData.customerAddr = item.customerAddress.addr
				this.formData.customerPhone = item.customerAddress.phone
				this.handleshow = false
				this.userData = item
				this.formData.customerId = item.label
				console.log(this.formData)
			},
			clearUserName() {
				this.handleshow = true
			},
			async handleSave() {
				// {"wsId":1, "type":"B", "customerId":1, "origin":"APP","salesId":1,"total":300,"cuser":"jack",
				// "expectTime":"2021-11-11"}
				// if (this.formData.deliveryDate == "") {
				// 	this.$message({
				// 		message: "请填写完发货时间",
				// 		type: "error"
				// 	})
				// 	return
				// }
				// if(this.formData.tags.length == 0){
				// 	this.$message({
				// 		message: "请选择订单所选标签",
				// 		type: "error"
				// 	})
				// 	return
				// }
				if(this.tableData.length == 0){
					this.$message({
						message: "请选择订购商品",
						type: "error"
					})
					return
				}
				this.formData.tags = this.formData.tags?this.formData.tags.toString():''
				const res = await getOrderAdd(this.formData)
				let list = []
				// [{"orderId":16, "productName":"白菜", "productId":"2", "qty":10, "unit":"袋", "price":"3350","subtotal":33500},
				// {"orderId":16, "productName":"大米", "productId":"3", "qty":10, "unit":"斤", "price":"3350","subtotal":33500}]
				let orderid = res.data.orderid
				console.log(orderid);
				this.tableData.forEach((item) => {
					let data = {
						orderId: orderid,
						productName: item.name,
						productId: item.id,
						qty: item.qty,
						unit: item.unit,
						price: parseInt(item.goodsPrice.price * 100),
						subtotal: parseInt(this.totalPrice),
						status:1
					}
					list.push(data)
				})
				let listres = await getOrderitemAdd(list)
				console.log(listres, "listres");
				if (listres.status == 200) {
					this.$message.success('提交成功')
					this.goBack()
				} else {
					this.$message.error('提交失败')
				}
				// if (res.data) {
				// 	this.$message.success('提交成功')
				// 	this.goBack()
				// }
			},
			async goBack() {
				const detailPath = await handleActivePath(this.$route, true)
				await this.$router.push('/order/orderlist')
				await this.delVisitedRoute(detailPath)
			},
			selectGoods(sel, row) {
				this.selectData = sel
			},
			checkPage(page) {
				this.dataFilter.current = page
				this.getListData()
			},
			sizeChange(e) {
				this.dataFilter.pagesize = e
				this.getListData()
			}
		},
	}
</script>

<style lang="scss" scoped>
	.contents {
		padding: 5px 15px 0;

		.neworder {
			// height: 400px;
			overflow: hidden auto;

			.newOrder-title {
				width: 100%;
				padding: 10px;
				font-size: 16px;
				text-align: left;
				border-bottom: 1px solid #eee;
				margin: 0;

				.newOrder-operation {
					float: right;
					margin-right: 10px;
					vertical-align: middle;
					font-size: 14px;
					color: #03ac54;

					span:not(:last-child) {
						margin-right: 10px;
					}
				}
			}

			.new-order-main {
				position: relative;
				border-bottom: 8px solid #f5f5f5;
				width: 100%;
				padding: 15px 10px;
			}

			.newOrder-address {
				width: 100%;
				padding: 10px;
				text-align: left;
				border-bottom: 8px solid #f5f5f5;
			}

			.newOrder-address>span {
				margin-right: 10px;
			}

			.newOrder-amount {
				padding: 10px;
				text-align: right;
				font-size: 14px;
				color: #ed3f14;
			}

			.newOrder-remark {
				margin-top: 10px;
				width: 100%;
				height: 50px;
				padding: 0 10px;
				border-bottom: 8px solid #f5f5f5;
			}

			.newOrder-feature {
				text-align: left;
				padding: 15px;
				border-top: 1px solid #eee;
			}
		}
	}
</style>
